package com.ruyuan2020.im.xx;

import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @author gaowei
 * @date 2025/3/5
 */
public class WorkerTask {

    // 线程池大小
    private final int POOL_SIZE = 3;
    // 数据拆分大小
    private final int SPLIT_SIZE = 4;
    private final String taskName;
    // 接收关闭信号，实现优雅停机
    protected volatile boolean shutdownFlag = false;

    // 构造函数
    public WorkerTask(String taskName) {
        this.taskName = taskName;
    }

    // 执行任务入口
    public void executeTask() {
        int cycleCount = 0;
        while (true) {
            System.out.println(taskName + ":Cycle-" + cycleCount + "-Begin");
            // 获取数据
            List<CustomEntity> taskData = fetchData();
            // 处理数据
            processTaskData(taskData);
            System.out.println(taskName + ":Cycle-" + cycleCount + "-End");
            if (shutdownFlag) {
                // 只有应用关闭，才会走到这里，用于实现优雅的下线
                break;
            }
            cycleCount++;
        }
        // 回收线程池资源
        TaskManager.releaseExecutor(taskName);
    }

    // 关闭任务
    public void shutdownTask() {
        // 关机
        shutdownFlag = true;
        System.out.println(taskName + " shutdown initiated");
    }

    // 处理数据逻辑
    private void processData(List<CustomEntity> data, CountDownLatch latch) {
        try {
            for (CustomEntity entity : data) {
                System.out.println(taskName + ":" + entity.toString() + ",ThreadName:" + Thread.currentThread().getName());
                Thread.sleep(1000L);
            }
        } catch (Exception e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
        } finally {
            if (latch != null) {
                latch.countDown();
            }
        }
    }

    // 处理单个任务数据
    private void processTaskData(List<CustomEntity> sourceData) {
        if (CollectionUtils.isEmpty(sourceData)) {
            return;
        }
        // 将数据拆成4份
        List<List<CustomEntity>> splitData = Lists.partition(sourceData, SPLIT_SIZE);
        final CountDownLatch latch = new CountDownLatch(splitData.size());

        // 并发处理拆分的数据，共用一个线程池
        for (final List<CustomEntity> data : splitData) {
            ExecutorService executorService = TaskManager.getOrInitializeExecutor(taskName, POOL_SIZE);
            executorService.submit(() -> processData(data, latch));
        }

        try {
            latch.await();
        } catch (Exception e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
        }
    }

    // 获取任务数据
    private List<CustomEntity> fetchData() {
        List<CustomEntity> data = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            data.add(new CustomEntity().setEntityName("Entity-" + i));
        }
        return data;
    }
}
